#!/usr/bin/env python
# coding=utf-8
# __author__ = 'Yunchao Ling'

from retrying import retry
from bs4 import BeautifulSoup
import re
import cStringIO
import pycurl
import sys
import os


@retry
def Get_PMC_Meta_By_PMCID(pmcid):
    url = 'http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi'
    buf = cStringIO.StringIO()
    c = pycurl.Curl()
    c.setopt(pycurl.POST, 1)
    c.setopt(c.URL, url)
    c.setopt(pycurl.HTTPPOST, [('db', 'pmc'), ('id', pmcid), ('retmode', 'xml')])
    c.setopt(c.WRITEFUNCTION, buf.write)
    c.perform()
    result = buf.getvalue()
    buf.close()
    c.close()
    if result.find("</pmc-articleset>") == -1:
        raise IOError("Invalid xml.")
    return result


def Search_IDs(article_string):
    pattern = re.compile("(<article-id.*?</article-id>)", re.I)
    m = re.findall(pattern, article_string)
    manuscript_id = None
    if len(m) > 0:
        for id_string in m:
            soup = BeautifulSoup(id_string, "xml")
            id_soup = soup.find("article-id")
            if id_soup != None:
                if id_soup["pub-id-type"] == "manuscript":
                    manuscript_id = id_soup.string
                    break
    return manuscript_id


if __name__ == '__main__':
    filename = sys.argv[1]
    if not os.path.exists(filename):
        print("No PMCIDs file.")
        sys.exit(0)
    infile = open(filename, "r")
    outfile = open(filename + ".publish", "w")
    for line in infile:
        line = line.rstrip()
        pmcid = line
        manuscript_id = Search_IDs(Get_PMC_Meta_By_PMCID(pmcid))
        if manuscript_id == None:
            print(pmcid + "\tpublish")
            outfile.write(pmcid + "\n")
            outfile.flush()
        else:
            print(pmcid + "\tmanuscript")
    outfile.close()
    infile.close()
